from google.appengine.ext import db
from google.appengine.api import users
import datetime
import logging
import Entities
import Contacts

#Activity data model
class ActivityModel(db.Model):
    author	   	= db.UserProperty(required=True)
    activity		= db.StringProperty()
    priority		= db.StringProperty()
    entityCode		= db.ReferenceProperty(reference_class=Entities.EntitiesModel,collection_name='EntitiesActivity')
    contact		= db.ReferenceProperty(reference_class=Contacts.ContactsModel,collection_name='ContactsActivity')
    shortDescription 	= db.StringProperty(required=True)
    longDescription  	= db.StringProperty(multiline=True)
    created	     	= db.DateTimeProperty(auto_now_add=True)
    updated	   	= db.DateTimeProperty(auto_now=True)
    dueDate	     	= db.DateTimeProperty(required=True)
    finished	     	= db.BooleanProperty()

def addActivity(vAuthor, vActivity, vPriority, vEntityCode, vContact, vShortDescription, vLongDescription, vDueDate, vFinished, user):
    """
    Add a new activity to the datastore.
  
    Returns  
	The id of the activity or None if the add failed.
    """
    logging.info('Start addActivity request')
    if vAuthor is None:
	return

    try:
	nActivity = ActivityModel(
		author = vAuthor,
		activity = vActivity,
		priority = vPriority,
		entityCode = Entities.getEntity(vEntityCode,user),
		contact = Contacts.getContact(vContact,user),		
		shortDescription = vShortDescription,
		longDescription = vLongDescription,
		dueDate = vDueDate,
		finished = vFinished)

	logging.info('before addActivity request')
	nActivity.put()
	logging.info('End addActivity successfully')
	return nActivity.key().id()
    except db.Error:
	logging.error('Error: addActivity %s ' %db.Error)
	return '#Error adding activity'

def updateActivity(ActivityID, vAuthor, vActivity, vPriority, vEntityCode, vContact, vShortDescription, vLongDescription, vDueDate, vFinished, user):
    """
    Update an Activity
    
    Returns the Activity ID or None if an error occurred
    """
    logging.info('Start updateActivity')
    
    if vAuthor is None:
      return

    try:
	def transact():
	    now = datetime.datetime.now()
	    currActivity=ActivityModel.get_by_id(int(ActivityID))
	    currActivity.author 		= vAuthor
	    currActivity.activity 		= vActivity
	    currActivity.priority 		= vPriority
	    currActivity.entityCode		= Entities.EntitiesModel.get_by_id(int(vEntityCode))
	    currActivity.contact 		= Contacts.ContactsModel.get_by_id(int(vContact))	    
	    currActivity.shortDescription 	= vShortDescription
	    currActivity.longDescription 	= vLongDescription
	    currActivity.dueDate 		= vDueDate
	    currActivity.finished 		= vFinished
	    currActivity.UpdatedBy		= vAuthor
	    currActivity.UpdatedOn		= now
	    currActivity.put()
	db.run_in_transaction(transact)
	
	logging.info('End updateActivity successfully')
	return ActivityID
    except db.Error:
	logging.error('Error: updateActivity')
	return None

def deleteActivity(ActivityID, user):
    """
    Delete an Activity
    
    Returns  
      1 or 0 denpending on success
    """
    logging.info('Start deleteActivity ID=: %s' %ActivityID)
    if user is None:
      return 0

    try:      
	def transact():
	    currActivity = ActivityModel.get_by_id(int(ActivityID))
	    currActivity.delete()
	db.run_in_transaction(transact)
	
	logging.info('End deleteActivity successfully ID=: %s' %ActivityID)
	return 1
    except db.Error:
	logging.error('#Error deleteActivity ID= %s' %ActivityID)
	return 0

def doneActivity(ActivityID, user):
    """
    Finish an Activity
    
    Returns  
      1 or 0 denpending on success
    """
    logging.info('Start doneActivity ID=: %s' %ActivityID)
    if user is None:
      return 0

    try:      
	def transact():
	    currActivity = ActivityModel.get_by_id(int(ActivityID))
	    currActivity.finished = True
            currActivity.put()
	db.run_in_transaction(transact)
	
	logging.info('End doneActivity successfully ID=: %s' %ActivityID)
	return 1
    except db.Error:
	logging.error('#Error doneActivity ID= %s' %ActivityID)
	return 0


def getActivities(user):
    """ 
    Returns  the entities list of the responsible user
    """
    
    if user is None:
      return 
    
    try:
	Activities = ActivityModel.gql("WHERE author = :author and finished=false", author=user)
  
	return Activities
    except db.Error:
	return None

def getActivitiesFilter(user, filterEntityCode, filterContact, filterActivity, filterPriority, sinceDate, toDate):
    """ 
    Returns the entities list filtered of the responsible user 
    """
    
    if user is None:
      return 
    
    try:
	args = []
	filter = "WHERE finished=false and author = :1"
	args.append(user)
	numFilter = 1
	
	if filterEntityCode:
	    numFilter += 1
	    filter += " and entityCode = :" + str(numFilter)
	    args.append(Entities.getKey(filterEntityCode, user))
	    
	if filterContact:
	    numFilter += 1
	    filter += " and contact = :" + str(numFilter)
	    args.append(Contacts.getKey(filterContact, user))

	if filterActivity:
	    numFilter += 1
	    filter += " and activity = :" + str(numFilter)
	    args.append(filterActivity)
	
	if filterPriority:
	    numFilter += 1
	    filter += " and priority = :" + str(numFilter)
	    args.append(filterPriority)
	
	if sinceDate:
	    numFilter += 1
	    filter += " and dueDate >= :" + str(numFilter)
	    args.append(sinceDate)
	
	if toDate:
	    numFilter += 1
	    filter += " and dueDate <= :" + str(numFilter)
	    args.append(toDate)

	Activities = ActivityModel.gql(filter, *args)
  
	return Activities
    except db.Error:
	logging.info('ERRO filter: %s' %filter)
	return None

def getActivity(ActivityID, user):
    """ 
    Returns the Activity with the ID = ActivityID
    """
    if user is None:
      return  
    
    try:
	oActivity = ActivityModel.get_by_id(int(ActivityID))
	logging.info('End getActivity successfully: %s' % oActivity.shortDescription)
	return oActivity

    except db.Error:
	logging.error('#Error getActivity ID= %s' %ActivityID)
	return None